package com.moyv.schoolbbs.ui.fragment;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.moyv.schoolbbs.R;
import com.moyv.schoolbbs.base.chat.data.DialogData;
import com.moyv.schoolbbs.base.chat.data.SealData;
import com.moyv.schoolbbs.bean.model.Dialog;
import com.moyv.schoolbbs.bean.model.Message;
import com.moyv.schoolbbs.bean.model.User;
import com.moyv.schoolbbs.config.AccountConstant;
import com.moyv.schoolbbs.ui.activity.BottomTabLayoutActivity;
import com.moyv.schoolbbs.ui.activity.ChatActivity;
import com.moyv.schoolbbs.ui.service.ChatService;
import com.moyv.schoolbbs.util.ToastUtils;
import com.stfalcon.chatkit.dialogs.DialogsList;
import com.stfalcon.chatkit.dialogs.DialogsListAdapter;

import java.util.Date;

public class MessageFragment extends Fragment {
    private Context context;
    private DialogsList dialogsList;
    private DialogsListAdapter<Dialog> dialogsListAdapter;
    private BottomTabLayoutActivity activity;

    private ServiceConnection conn;
    private ChatService chatService;

    private DialogData dialogData;
    private Dialog saveDialog;


    public static MessageFragment newInstance(String title) {
        Bundle arguments = new Bundle();
        arguments.putString("TITLE", title);
        MessageFragment fragment = new MessageFragment();
        fragment.setArguments(arguments);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_message, container, false);
        context = getContext();
        activity = (BottomTabLayoutActivity) getActivity();
        dialogsList = root.findViewById(R.id.dialogsList);
        dialogData = new DialogData(context, String.valueOf(AccountConstant.ACCOUNT));
        initDialogList();

        //绑定Chat后台服务
        Intent intent = new Intent(context, ChatService.class);
        System.out.println("context,this" + this);
        initConn();
        context.bindService(intent, conn, Context.BIND_AUTO_CREATE);

        ToastUtils.showToast(context, "MessageFragment", false);
        return root;
    }

    //构造列表
    private void initDialogList() {
        dialogsListAdapter = new DialogsListAdapter<>((imageView, url, payload) -> {
            Glide.with(context).load(url).into(imageView);
        });
        dialogsListAdapter.addItems(dialogData.getLocalRecord());//数据源
        dialogsListAdapter.setOnDialogClickListener(dialog -> {
            openChat(dialog);
        });//聊天界面
        dialogsListAdapter.setOnDialogLongClickListener(dialog -> ToastUtils.show(dialog.getDialogName()));
        dialogsList.setAdapter(dialogsListAdapter);
    }

    private void openChat(Dialog dialog) {
        ChatActivity.open(context, chatService.getMessagesServer(), dialog, dialogData);
        saveDialog = dialog;
        dialog.setUnreadCount(0);
        dialogsListAdapter.notifyDataSetChanged();
        dialogData.updateDialogUnreadCount(dialog.getId(), 0);
    }

    //绑定service回调
    private void initConn() {
        conn = new ServiceConnection() {
            /**
             * 与服务器端交互的接口方法 绑定服务的时候被回调，在这个方法获取绑定Service传递过来的IBinder对象，
             * 通过这个IBinder对象，实现宿主和Service的交互。
             */
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                ChatService.MBinder mBinder = (ChatService.MBinder) service;
                chatService = mBinder.getService();
                activity.setChatService(chatService);
                //消息监听回调接口
                chatService.setOnProgressListener((message) -> {
                    System.out.println("回调接受消息：" + message.getBody());
                    String n = message.getFrom().getLocalpartOrThrow().toString();
                    String mes = message.getBody();
                    String Name = chatService.searchFirst(n).getName();
                    dialogData.saveMessage(n, n, mes, true);
                    Dialog itemById = dialogsListAdapter.getItemById(n);
                    System.out.println("itemByid:" + itemById);
                    if (itemById == null) {
                        Dialog dialog = dialogData.CreateDialog(n, Name, mes);
                        activity.runOnUiThread(() -> {
                            dialogsListAdapter.addItem(0, dialog);
                        });
                    } else {
                        itemById.setLastMessage(SealData.getMessage(n, mes, new Date()));
                        itemById.setUnreadCount(itemById.getUnreadCount() + 1);
//                        dialogsListAdapter.
                        activity.runOnUiThread(() -> {
                            dialogsListAdapter.notifyDataSetChanged();
                        });
                        dialogData.updateDialogUnreadCount(n, itemById.getUnreadCount());
                    }
                });

                chatService.initService();
            }

            /**
             * 当取消绑定的时候被回调。但正常情况下是不被调用的，它的调用时机是当Service服务被意外销毁时，
             * 例如内存的资源不足时这个方法才被自动调用。
             */
            @Override
            public void onServiceDisconnected(ComponentName name) {
                ToastUtils.showToast(context, "Chat后台服务被终结！！！", true);
                System.out.println("Chat后台服务被终结！！！");
                chatService = null;
            }
        };
    }

    @Override
    public void onResume() {
        super.onResume();
        if (saveDialog != null) {
            saveDialog.setUnreadCount(0);
            Message message = dialogData.getLastMessage(saveDialog.getId());
            saveDialog.setLastMessage(message);
            dialogsListAdapter.notifyDataSetChanged();
            dialogData.updateDialogUnreadCount(saveDialog.getId(), 0);
            saveDialog = null;
        }
        System.out.println(dialogData.getName() + "," + AccountConstant.ACCOUNT);
        if (!dialogData.getName().equals(String.valueOf(AccountConstant.ACCOUNT))) {
            dialogData = new DialogData(context, String.valueOf(AccountConstant.ACCOUNT));
            dialogsListAdapter.clear();
            dialogsListAdapter.addItems(dialogData.getLocalRecord());
        }
        if (!AccountConstant.LOGIN) {
            dialogsListAdapter.clear();
        }
        ToastUtils.showToast(context, "onResume", false);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.add(0, 1, 0, "添加好友").setIcon(R.drawable.btn_white_add)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
//        //对整个菜单进行显示
//        menu.setGroupVisible(R.menu.mymenu, true);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == 1) {
            if (!AccountConstant.LOGIN) {
                ToastUtils.showToast(context,"请先登录",false);
                return false;
            }
            EditText editText = new EditText(context);
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("请输入账号：");
            builder.setView(editText);
            builder.setPositiveButton("搜索", (dialog, which) -> {
                User user = chatService.searchFirst(editText.getText().toString());
                if (user != null) {
                    if (user.getId().equals(AccountConstant.ACCOUNT+"")){
                        ToastUtils.showToast(context,"人格分裂患者请及时就医",false);
                        return;
                    }
                    AlertDialog.Builder check = new AlertDialog.Builder(context);
                    check.setTitle("找到用户：" + user.getName());
                    check.setPositiveButton("连接", (dialog1, which1) -> {
                        Dialog itemById = dialogsListAdapter.getItemById(user.getId());
                        if (itemById == null) {
                            Dialog createDialog = dialogData.CreateDialog(user.getId(), user.getName(), "");
                            openChat(createDialog);
                            dialogsListAdapter.addItem(0, createDialog);
                        } else {
                            openChat(itemById);
                        }
                    });
                    check.setNegativeButton("取消", (dialog1, which1) -> {
                    });
                    check.show();
                } else {
                    ToastUtils.showToast(context, "未找到", false);
                }
            });
            builder.setNegativeButton("取消", (dialog, which) -> {
            });
            builder.show();
            return true;
        }
        return false;
    }
}
